<template>
  <div class="invoice-record">
    <section class="header">
      <a-page-header title="发票记录">
        <template #extra>
          <a-button @click="btnImport">
            <UploadOutlined/>
            批量导入
          </a-button>
        </template>
      </a-page-header>
    </section>
    <section class="content">
      <!-- 统计数据 -->
      <section class="show-data">
        <a-row
            type="flex"
            justify="space-around"
            align="middle"
            :style="{ height: $store.getters.isMobile ? undefined : '80px' }"
            :gutter="[12, 12]"
        >
          <a-col :xs="12" :md="4">
            <a-statistic :value="showData.apply_amounts">
              <template #title>
                <span>申请开票金额</span>
              </template>
            </a-statistic>
          </a-col>
          <a-col :xs="12" :md="4">
            <a-statistic :value="showData.invoice_amounts">
              <template #title>
                <span>已开票</span>
                <span>（{{ showData.invoice_total || 0 }}张）</span>
              </template>
            </a-statistic>
          </a-col>
          <a-col :xs="12" :md="4">
            <a-statistic :value="showData.can_amounts">
              <template #title>
                <span>待开票</span>
              </template>
            </a-statistic>
          </a-col>
        </a-row>
      </section>
      <!-- 表格数据 -->
      <section class="table-data">
        <a-table
            sticky
            :dataSource="dataList"
            :columns="columns"
            :loading="loading"
            :pagination="pagination"
            @change="handleTableChange"
            rowKey="id"
            :scroll="{ x: 'max-content' }"
            class="mt-10"
            :customRow="customRow"
        >
          <template #title>
            <a-row
                type="flex"
                justify="space-between"
                align="middle"
                class="plr-10"
            >
              <a-form layout="inline">
                <a-col>
                  <a-form-item label="创建日期区间">
                    <a-range-picker
                        v-model:value="rangeTime"
                        :placeholder="['创建起始时间', '创建结束时间']"
                        :value-format="dateFormatStr"
                        :ranges="ranges"
                        @change="handleRangePickerChange"
                    />
                  </a-form-item>
                </a-col>
                <a-col>
                  <a-space>
                    <a-button type="primary" @click="toSearch">搜索</a-button>
                    <a-button @click="reSet">重置</a-button>
                  </a-space>
                </a-col>
              </a-form>

              <a-col>
                <custom-columns
                    :colUrl="colUrl"
                    type="user_invoice_list_field"
                    resetType="autoInvoiceListColumn"
                    @getColumns="getColumns"
                />
              </a-col>
            </a-row>
          </template>
          <!-- 搜索 -->
          <template
              #customFilterDropdown="{
              setSelectedKeys,
              selectedKeys,
              confirm,
              clearFilters,
              column,
            }"
          >
            <div style="padding: 8px">
              <a-input
                  ref="searchInput"
                  :placeholder="`搜索 ${column.title}`"
                  :value="selectedKeys[0]"
                  style="width: 188px; margin-bottom: 8px; display: block"
                  @change="
                  (e) => setSelectedKeys(e.target.value ? [e.target.value] : [])
                "
                  @pressEnter="
                  handleSearch(selectedKeys, confirm, column.searchKey)
                "
              />
              <a-button
                  type="primary"
                  size="small"
                  style="width: 90px; margin-right: 8px"
                  @click="handleSearch(selectedKeys, confirm, column.searchKey)"
              >
                搜索
              </a-button>
              <a-button
                  size="small"
                  style="width: 90px"
                  @click="handleReset(clearFilters, confirm, column.searchKey)"
              >
                重置
              </a-button>
            </div>
          </template>
          <template #customFilterIcon="{ filtered, column }">
            <template v-if="column.key === 'invoice_type_txt'">
              <FilterFilled/>
            </template>
            <template v-else-if="column.key === 'invoice_status_txt'">
              <FilterFilled/>
            </template>
            <template v-else-if="column.key === 'build_name'">
              <FilterFilled/>
            </template>
            <template v-else>
              <SearchOutlined
                  :style="{ color: filtered ? '#108ee9' : undefined }"
              />
            </template>
          </template>

          <template #bodyCell="{ text, record, index, column }">
            <template v-if="column.key === 'invoice_status_txt'">
              <!-- 发票状态 -->
              <a-tag v-if="record.invoice_status == 1" color="#1677ff">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.invoice_status == 2" color="#00b578">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.invoice_status == 3" color="#ff3141">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.invoice_status == 6" color="#999999">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.invoice_status == 7" color="#e3c738">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.invoice_status == 8" color="#cacaca">
                {{ text }}
              </a-tag>
              <a-tag v-else-if="record.invoice_status == 9" color="#ff3141">
                {{ text }}
              </a-tag>
              <a-tag v-else color="#666666">{{ text }}</a-tag>
            </template>
          </template>
        </a-table>
      </section>
    </section>

    <!--  批量导入  -->
    <Import
        :visible="visibleImport"
        title="导入实收发票"
        from="invoice"
        :importUrl="importUrl"
        :downloadTemUrl="downloadTemUrl"
        :showError="true"
        @cancelBtn="visibleImport = false"
        @refresh="importSuccess"
    />
  </div>
</template>

<script>
import {defineComponent, reactive, toRefs, computed, toRaw, onActivated} from "vue";
import {useRouter} from "vue-router";
import request from "../../../common/utils/request";
import CustomColumns from "../../../components/CustomColumns/index.vue";
import {
  SearchOutlined,
  UploadOutlined,
  FilterFilled,
} from "@ant-design/icons-vue";
import Import from "@/views/setting/DepartmentUser/modules/Import.vue";
import utils from '@/common/utils/utils'
import dayjs from 'dayjs'

export default defineComponent({
  name: "invoiceList",
  components: {
    UploadOutlined,
    SearchOutlined,
    CustomColumns,
    Import,
    FilterFilled,
  },
  setup() {
    const $router = useRouter();

    const state = reactive({
      showData: {},
      colUrl: {server: "/org", url: "/contract/invoiceListColumn"},
      columns: [],
      loading: false,
      rangeTime: [],
      page: 1,
      pageSize: 10,
      total: 0,
      dataList: [],
      searchInput: null,
      initData: {},
      visibleImport: false,
      importUrl: {
        server: "/org",
        url: "/invoice/import",
      },
      downloadTemUrl: {
        server: "/org",
        url: "/invoice/import/demoFile",
      },
      ranges: {
        '今天': [dayjs(), dayjs()],
        '昨天': [dayjs().subtract(1, 'day'), dayjs().subtract(1, 'day')],
        '本月': [dayjs().startOf('month'), dayjs()],
        '上月': [dayjs().add(-1, 'month').startOf('month'), dayjs().add(-1, 'month').endOf('month')],
        '本年': [dayjs().startOf('year'), dayjs()],
      }
    });

    const searchForm = reactive({
      start_time: undefined,
      end_time: undefined,
      invoice_type: undefined,
      invoice_status: undefined,
      build_id: undefined,
      invoice_code: undefined,
      owner_name: undefined,
      cuser_name: undefined,
    });

    // 自定义行
    const customRow = (record) => {
      return {
        style: {
          cursor: "pointer",
        },
        onClick: () => handleTableRowClick(record),
      };
    };
    // 点击行
    const handleTableRowClick = (record) => {
      $router.push({
        name: "invoiceDetail",
        query: {group_key: record.group_key},
      });
    };

    /* 获取列表展示项 */
    const searchCols = ["owner_name", "cuser_name", "invoice_code"];
    const filterCols = ["invoice_type_txt", "invoice_status_txt", "build_name"];
    const customCols = ["invoice_status_txt"];
    const getColumns = (columns) => {
      state.columns = [];
      columns.forEach((item) => {
        let newItem = {
          title: item.title,
          key: item.key,
          dataIndex: item.key,
          width: 160,
        };

        if (item.key == "invoice_type_txt") {
          newItem.width = 200;
        }
        if (searchCols.includes(item.key)) {
          newItem.searchKey = item.key == "owner_name" ? "keywords" : item.key;
          newItem.customFilterDropdown = true;
          newItem.onFilterDropdownVisibleChange = (visible) =>
              searchInputFocus(visible);
        }
        if (filterCols.includes(item.key)) {
          newItem.filters = state.initData[valueMap[item.key]];
          newItem.filterMultiple = false;
        }
        state.columns.push(newItem);
      });
      console.log("getColumns", toRaw(state.columns));
    };
    const valueMap = {
      invoice_type_txt: "invoice_type",
      invoice_status_txt: "invoice_status",
      build_name: "build_id",
    };

    /* 搜索相关 */
    const searchInputFocus = (visible) => {
      if (visible) {
        setTimeout(() => {
          state.searchInput.focus();
        }, 100);
      }
    };
    const handleSearch = (selectedKeys, confirm, searchKey) => {
      if (selectedKeys && selectedKeys.length > 0) {
        searchForm[searchKey] = selectedKeys[0];
      }
      confirm();
    };
    const handleReset = (clearFilters, confirm, searchKey) => {
      searchForm[searchKey] = undefined;
      clearFilters();
      confirm();
    };
    const handleRangePickerChange = (date, dateString) => {
      searchForm.start_time = dateString[0] || undefined;
      searchForm.end_time = dateString[1] || undefined;
    };

    /* 获取统计数据 */
    const getShowData = () => {
      request.get("/org", "/bill/invoiceStatistics").then((res) => {
        state.showData = res.data;
      });
    };
    /* 获取列表数据 */
    const getDataList = () => {
      state.loading = true;
      request
          .get("/org", "/bill/invoiceList", {
            page: state.page,
            limit: state.pageSize,
            ...searchForm,
          })
          .then((res) => {
            state.loading = false;
            state.dataList = res.list;
            state.total = res.total;
          });
    };
    const pagination = computed(() => ({
      total: state.total,
      current: state.page,
      pageSize: state.pageSize,
      showSizeChanger: true,
    }));
    const handleTableChange = (pager, filters) => {
      state.page = pager.current;
      state.pageSize = pager.pageSize;
      if (Object.keys(filters).length) {
        for (let key in filters) {
          const formKey = valueMap[key];
          if (formKey) {
            searchForm[formKey] =
                filters[key] && filters[key].length ? filters[key][0] : null;
          }
        }
      }
      getDataList();
    };
    /* 获取初始化数据 */
    const getInitData = () => {
      request.get("/org", "/bill/invoiceListInit").then((res) => {
        const {initData} = res;
        state.initData = {
          invoice_type: initData.invoiceType.map((item) => ({
            text: item.name,
            value: item.key,
          })),
          invoice_status: initData.invoiceStatus.map((item) => ({
            text: item.name,
            value: item.key,
          })),
          build_id: initData.buildNames.map((item) => ({
            text: item.name,
            value: item.key,
          })),
        };
      });
    };

    const btnImport = () => {
      state.visibleImport = true;
    };

    const importSuccess = () => {
      state.visibleImport = false;
      getDataList();
    };

    const init = () => {
      getInitData();
      getShowData();
      getDataList();
    };

    onActivated(() => {
      init();
    });

    const toSearch = () => {
      getDataList();
    }

    const reSet = () => {
      state.rangeTime = [];
      searchForm.start_time = undefined;
      searchForm.end_time = undefined;
      getDataList();
    }

    return {
      dateFormatStr: "YYYY-MM-DD",
      pagination,
      ...toRefs(state),
      customRow,
      getColumns,
      handleTableChange,
      handleSearch,
      handleReset,
      handleRangePickerChange,
      btnImport,
      importSuccess,
      toSearch,
      reSet
    };
  },
});
</script>

<style lang="less" scoped>
.invoice-record {
  .header {
    background: #fff;
    margin-left: 1px;
  }

  .content {
    margin: 10px;

    .show-data {
      background: #fff;
      padding: 10px 0;
    }
  }
}
</style>
